package org.example.client;

import okhttp3.*;

import java.io.IOException;

public class MyClient {
    private static final OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) {
        final int port = 8801;
        useSync(port);
        useAsync(port);
    }

    public static void useSync(int port) {
        System.out.println("use sync ----------------");
        Request request = new Request.Builder()
                .url("http://127.0.0.1:" + port)
                .get()
                .build();

        try (Response response = client.newCall(request).execute()) {
            Headers responseHeaders = response.headers();
            for (int i = 0, size = responseHeaders.size(); i < size; ++i) {
                System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
            }

            if (response.isSuccessful()) {
                ResponseBody responseBody = response.body();
                if (responseBody != null) {
                    System.out.println(responseBody.string());
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void useAsync(int port) {
        System.out.println("use async ---------------");
        Request request = new Request.Builder()
                .url("http://127.0.0.1:" + port)
                .get()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody responseBody = response.body()) {
                    if (!response.isSuccessful()) {
                        throw new IOException("Unexpected code " + response.code());
                    }

                    Headers responseHeaders = response.headers();
                    for (int i = 0, size = responseHeaders.size(); i < size; ++i) {
                        System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                    }

                    if (responseBody != null) {
                        System.out.println(responseBody.string());
                    }
                }
            }
        });
    }
}
